package com.dmapp.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;

import android.os.Handler;
import android.os.Message;
import android.util.Log;


/* @author sinawear
 * 540126629@qq.com
 */
public abstract class NetHelper {
	
	static final String TAG ="NetHelper";
	
	
	 Handler handler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			
			String str = (String)msg.obj;
			//System.out.println(str);
			Log.e(TAG, str);
			
			try{
				
				onComplete( str );
			}
			catch(JSONException e){
				
				e.printStackTrace();
				System.out.println("JSONException: " + e.toString());
			}
			
		};
	};
	
//	static String strNetRespone ="";  还是发送吧.. 内存不释放...
	
	
	// 需要的两个参数
	String url ="";
	ArrayList<BasicNameValuePair> map = new ArrayList<BasicNameValuePair>();
	
	
	public abstract String init( ArrayList<BasicNameValuePair> map);
	public abstract void onComplete(String message) throws JSONException;  //并不会强制要函数体内,必须会有json异常跑出呢..
	
	
	public void UI_init(){ 
		
	}
	
	public void start_GET(){
	
		
		UI_init();
		
		
		new Thread(){
			
			public void run() {   
				
				url =init( map);
				if(url.length() == 0 )
					return;
				
				
				String strNetRespone = httpGetHelper(map);
				Message msg = new Message();
				msg.obj = strNetRespone;
				handler.sendMessage(msg);
				
			//	onComplete(httpGetHelper(map));
				
			};
		}.start();
		
		
	}
	
	public void start_POST(){
		
		
		UI_init();
		

		
		new Thread(){
			
			public void run() {
				
				url =init( map);
				if(url.length() == 0 )
					return;
				
				String strNetRespone = httpPostHelper(map);
				Message msg = new Message();
				msg.obj = strNetRespone;
				handler.sendMessage(msg);
			//	onComplete(httpPostHelper(map));
				
			};
		}.start();
		
		
	}
	
	
	
	private String httpGetHelper(ArrayList<BasicNameValuePair> requestParams) {
		
		HashMap<String, String> parameters = new HashMap<String, String>();
		for(BasicNameValuePair basic : requestParams){
			
			parameters.put(basic.getName(), basic.getValue());
		}
		
		String jsonString = "1";
		InputStream inputStream = null;
		try {
			StringBuilder params = new StringBuilder("");
			if (parameters != null && parameters.size() > 0) { //添加参数
				params.append("?");
				
				for (Map.Entry<String, String> entry : parameters.entrySet()) {
					params.append(entry.getKey());
					params.append("=");
					params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
					params.append("&");
				}
			}
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
			HttpConnectionParams.setSoTimeout(httpParams, 20000); //
			HttpClient client = new DefaultHttpClient(httpParams);

			HttpGet request = new HttpGet(url + params);
			Log.e(TAG, "------------------------------------------------");
			Log.e(TAG, "URL=" + url + params);
			HttpResponse response = client.execute(request);

			HttpEntity httpEntity = response.getEntity();
			if (response.getStatusLine().getStatusCode() == 200) {
				inputStream = httpEntity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(inputStream));
				String result = "";
				String line = "";
				while ((line = reader.readLine()) != null) {
					result = result + line;
				}
				inputStream.close();
				jsonString = result;
			}

			return jsonString;

		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, e.toString());
			return "";
		}
		
	}
	
	
	private String httpPostHelper(ArrayList<BasicNameValuePair> parameters) {
		String jsonString = "";
		try {
	
			HttpPost post = new HttpPost( url );
			Log.e(TAG, "------------------------------------------------");
			Log.e(TAG, "url=" +  url );
			Log.e(TAG, "parameters=" + parameters.toString());
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
			HttpConnectionParams.setSoTimeout(httpParams, 1*60*1000);
			post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
			HttpResponse response = new DefaultHttpClient(httpParams)
					.execute(post);
			if (response.getStatusLine().getStatusCode() == 200)
				jsonString = EntityUtils
						.toString(response.getEntity(), "UTF-8");

			return jsonString;

		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, e.toString());
			return jsonString;
		}
		
	}
	
	
	
	
}
